package com.powerunion.extjs;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.powerunion.extjs.utils.Path;


public class XmlParser {
	/**
	 * 获取数据查询语句
	 * @param basepara
	 * @throws Exception
	 */
	public  void loadSql(BasePara basepara) throws Exception {
		try {
			String fullpath = basepara.getSqlpath();
			String sqlpath="";
			String filename="";
			if(fullpath.indexOf("//")>=0){
//				System.out.println(fullpath);
				String[] p = fullpath.split("//");
				sqlpath=p[1];
				filename="sqlfolder"+ File.separator+p[0]+".xml";
			}else{
				sqlpath=fullpath;
				filename=basepara.getXmlFileName();
			}
			String configFileName = Path.getFullPathRelateClass("../../..", XmlParser.class)
			+ File.separator+filename;
//			System.out.println(configFileName+"*************");
//			System.out.println(sqlpath);
			Element el = this.getNodeByPath(configFileName, sqlpath);
			String type = el.getAttribute("type");
			
			if("".equals(type)) type="sql";
			NodeList nl = el.getChildNodes();
			String sql="";
			String query_sql=basepara.getQueryStr();
			String group_sql="";
			String search_sql="";
			String sum_sql="";
			for(int j=0;j<nl.getLength();j++){
				Node node= nl.item(j);
//				System.out.println(node.getNodeName()+"|"+node.getNodeValue());
//				System.out.println("-------------"+nl.getLength());
				if(nl.getLength()==1){
					sql = node.getNodeValue();
					break;
				}
				if("main_sql".equals(node.getNodeName())){
					sql = node.getFirstChild().getNodeValue();
				}
				if("sum_sql".equals(node.getNodeName())){
					sum_sql = node.getFirstChild().getNodeValue();
				}					
				if("query_sql".equals(node.getNodeName())){
					query_sql = node.getFirstChild().getNodeValue();
				}	
				if("group_sql".equals(node.getNodeName())){
					group_sql = node.getFirstChild().getNodeValue();
				}	
				if("search_sql".equals(node.getNodeName())){
					search_sql = node.getFirstChild().getNodeValue();
				}	
				
			}
			basepara.setSql(sql);
			basepara.setSumsql(sum_sql);
			basepara.setQueryStr(query_sql);
			basepara.setGroupSql(group_sql);
			basepara.setType(type);
			
			Map tree = new HashMap();
			String depth = el.getAttribute("depth");
			tree.put("depth", depth==null ? "" : depth.trim()); 
			tree.put("search_sql", search_sql==null ? "" : search_sql); 
			basepara.setTreeCfg(tree);
			if("".equals(sql))throw new Exception("xml没有配置sqlpath:"+sqlpath);
		} catch (Exception e) {
			throw new Exception("get sql error-->"+e.getMessage(),e.getCause());
		}
	}	
	
	private String getAttribute(Node node, String attrname) {
		Element el = (Element)node;
		String attrvalue = el.getAttribute(attrname);
		return attrvalue == null ? "" : attrvalue;
	}

	/**
	 * 根据路径，找到节点
	 * @param configfile
	 * @param sqlpath
	 * @return
	 * @throws Exception
	 */
	private Element getNodeByPath(String configfile,String sqlpath) throws Exception{
		String[] depthsnode = sqlpath.split("\\/");
		Document doc = this.getXml(configfile);
		Element root = (Element)doc.getFirstChild();
		for(int k=0;k<depthsnode.length;k++){
			NodeList nl = root.getChildNodes();
			for(int j=0;j<nl.getLength();j++){
//				System.out.println("node:"+nl.item(j).getNodeName());
				if(depthsnode[k].equals(nl.item(j).getNodeName())){
					if(k==depthsnode.length-1) return (Element)nl.item(j);
					root = (Element) nl.item(j);
					break;
				}
			}
		}
		throw new Exception("not find node:"+sqlpath);
	}
	
	private Document getXml(String configFileName) throws Exception {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(configFileName);
			doc.normalize();
			return doc;
		} catch (Exception e) {
			throw new Exception("get xml file error-->"+e.getMessage(),e.getCause());
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		System.out.println("Item".toLowerCase());
		// TODO Auto-generated method stub
		XmlParser xp = new XmlParser();
		BasePara bp = new BasePara();
		bp.setSqlpath("b/town_person_sum");
		try {
			xp.loadSql(bp);
			System.out.println(bp.getType());
			System.out.println(bp.getSql());			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
